<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\Controller;
use App\Models\Config;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ConfigController extends Controller
{

  // 配置列表
  public function index(Request $request)
  {
    $cates = Config::getList($request);
    return $this->success($cates);
  }

  // 配置详情
  public function detail($id)
  {
    $cateInfo = Config::getInfoById($id);
    return $this->success($cateInfo);
  }

  public function detailByCode($code)
  {
    $cateInfo = Config::getInfoByCode($code);
    return $this->success($cateInfo);
  }

  // 新增配置
  public function add(Request $request)
  {
    $data = $request->all();
    $rule = [
      'name'     => 'required',
      'code'     => 'required',
      'content'  => 'reqiured',
    ];
    $message = [
      'name.required'       => '配置名称不能为空',
      'code'                => '配置编号不能为空',
      'content'             => '配置内容不能为空',
    ];
    $validated = $this->validator($data, $rule, $message);
    if (is_bool($validated)) {
      $cateInfo = DB::table('configs')->where('code', $request->code)->first();
      if($cateInfo && $cateInfo->id) {
        return $this->failed('配置编号已存在');
      }
      $insertData = [
        'name' => $request->name ?? '',
        'code' => $request->code ?? '',
        'content' => $request->content ?? '',
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s'),
      ];
      $result = DB::table('configs')->insert($insertData);
      return $this->success();
    } else {
      return $validated;
    }
  }

  // 修改配置
  public function update(Request $request)
  {
    $cateInfo = DB::table('configs')->where('code', $request->code)->first();
    if ($cateInfo && $cateInfo->id) {
      $updateData = [
        'name' => $request->name ?? $cateInfo->name,
        'code' => $request->code ?? $cateInfo->code,
        'content' => $request->content ?? $cateInfo->content,
        'updated_at' => date('Y-m-d H:i:s'),
      ];
      $result = DB::table('configs')->where('code', $request->code)->update($updateData);
      if ($result) {
        return $this->success();
      }
      return $this->failed('修改失败');
    } else {
      return $this->failed('配置不存在');
    }
  }
}
